package cn.hackcloud.concurrency.eda;

import java.util.concurrent.TimeUnit;

public class AsyncEventDispatcherExample {
    static class AsyncInputEventHandler extends AsyncChannel {
        private final AsyncEventDispatcher dispatcher;

        public AsyncInputEventHandler(AsyncEventDispatcher dispatcher) {
            this.dispatcher = dispatcher;
        }

        @Override
        protected void handle(Event message) {
            EventDispatcherExample.InputEvent inputEvent = (EventDispatcherExample.InputEvent) message;
            int result = inputEvent.getX() + inputEvent.getY();
            dispatcher.dispatch(new EventDispatcherExample.ResultEvent(result));
        }
    }

    //主要用于处理InputEvent,但是需要继承AsyneChannel
    static class AsyncResultEventHandler extends AsyncChannel {
        @Override
        protected void handle(Event message) {
            EventDispatcherExample.ResultEvent resultEvent =
                    (EventDispatcherExample.ResultEvent) message;
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("The result is:" + resultEvent.getResult());
        }

        public static void main(String[] args) {
            //定义AsyncEventDispatcher
            AsyncEventDispatcher dispatcher = new AsyncEventDispatcher();
            //注册Event和Channel之间的关系
            dispatcher.registerChannel(EventDispatcherExample.InputEvent.class, new AsyncInputEventHandler(dispatcher));
            dispatcher.registerChannel(EventDispatcherExample.ResultEvent.class, new
                    AsyncResultEventHandler());
            //提交需要处理的Message
            dispatcher.dispatch(new EventDispatcherExample.InputEvent(1, 2));
        }

    }
}
